package com.hqd.ch03.v26.tx.transaction.interceptor;

/**
 * 回滚规则
 */
public class RollbackRuleAttribute {
    public static final RollbackRuleAttribute ROLLBACK_ON_RUNTIME_EXCEPTIONS =
            new RollbackRuleAttribute(RuntimeException.class);


    private final String exceptionPattern;


    public RollbackRuleAttribute(Class<?> exceptionType) {
        if (!Throwable.class.isAssignableFrom(exceptionType)) {
            throw new IllegalArgumentException(
                    "Cannot construct rollback rule from [" + exceptionType.getName() + "]: it's not a Throwable");
        }
        this.exceptionPattern = exceptionType.getName();
    }

    public RollbackRuleAttribute(String exceptionPattern) {
        this.exceptionPattern = exceptionPattern;
    }


    public String getExceptionName() {
        return this.exceptionPattern;
    }

    public int getDepth(Throwable exception) {
        return getDepth(exception.getClass(), 0);
    }


    private int getDepth(Class<?> exceptionType, int depth) {
        if (exceptionType.getName().contains(this.exceptionPattern)) {
            return depth;
        }
        if (exceptionType == Throwable.class) {
            return -1;
        }
        return getDepth(exceptionType.getSuperclass(), depth + 1);
    }
}
